// JavaScript Document
function ge(str) {
	return document.getElementById(str);
}

function checkThisBox(obj) {
	if(obj) {
		if(obj.checked){
			obj.parentNode.className = 'selected';
			} else {
			obj.parentNode.className = '';
		}
	}
}

// formats phone numbers as user types input
// usage: <input onkeypress="formatPhoneNum(this)"
function formatPhoneNum(e) { 
	var PhoneLength;
	PhoneLength = e.value.length;
	// puts in the first dash 
	if (PhoneLength==4 && e.value.substring(2,3) != '-'){
		e.value = e.value.substring(0,3) + '-' + e.value.substring(3,PhoneLength);
	}
	// stepping over where the dash usually goes
	if (PhoneLength==9 && e.value.substring(7,8) != '-'){
		e.value = e.value.substring(0,7) + '-' + e.value.substring(7,PhoneLength);
	}
	// remove double dash
	e.value = e.value.replace('--','-');
}

function cancelModify() {
	location.href = 'index.cfm';
}

function showHideTimes(obj) {
	var d = '';
	if(obj.checked) {
		d = 'none';
	}
	ge('start_end_times').style.display = d;
}

/*
	calculates the duration of time between two times
	assumes the times are in a pair of 3 select boxes hh : mm tt
	Automatically puts the duration in the duration object as inner HTML
*/
function calcDuration() {
	var h1 = document.getElementById('START_HOUR');
	var m1 = document.getElementById('START_MINUTE');
	var t1 = document.getElementById('START_AMPM');
	var h2 = document.getElementById('END_HOUR');
	var m2 = document.getElementById('END_MINUTE');
	var t2 = document.getElementById('END_AMPM');3
	var d = document.getElementById('duration');
	
	// create the date/time objects to hold the times
	var time1 = new Date();
	var time2 = new Date();
	
	// convert hours to 24 hr format
	/*
		Since the values in the hour drop down are 01 - 12, parseInt needs to have a radix of 10
		# If the string begins with "0", the radix is 8 (octal). This feature is deprecated
		# If the string begins with any other value, the radix is 10 (decimal)
	*/
	var tempH1 = parseInt(h1.value,10);
	if(tempH1 < 12 && t1.value == 'PM') {
		tempH1 = tempH1 + 12;
	}
	if(tempH1 == 12 && t1.value == 'AM') {
		tempH1 = 0;
	}
	var tempH2 = parseInt(h2.value,10);
	if(tempH2 < 12 && t2.value == 'PM') {
		tempH2 = tempH2 + 12;
	}
	if(tempH2 == 12 && t2.value == 'AM') {
		tempH2 = 0;
	}
	
	// set the times on the dates objects
	time1.setHours(tempH1,parseInt(m1.value));
	time2.setHours(tempH2,parseInt(m2.value));
	
	// calculate time difference in milliseconds
	var timeDiff = time2.getTime() - time1.getTime();
	timeDiff = timeDiff / 1000 / 60; // returns total minutes
	
	var timeDiffH = Math.floor(timeDiff / 60);	// return hours
	var timeDiffM = timeDiff - timeDiffH * 60;	// returns minutes
	
	if(d) {
		d.innerHTML 
			= 'Duration: ' 
				+ String(timeDiffH) + 'h ' 
				+ String(timeDiffM) + 'm';
	}
}

/*
	COOKIE HANDLING
*/

function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
         offset += search.length          // set index of beginning of value
         end = document.cookie.indexOf(";", offset)         
 // set index of end of cookie value      
	if (end == -1)   end = document.cookie.length         
	return unescape(document.cookie.substring(offset, end)) ;      }    }
}
function setCookie(name,value,days) {
    if (days == null) {
		setCookie1(name,value) ;
    } else {
		today = new Date();
		expiredate = new Date();
		expiredate.setTime(today.getTime()+days*60*60*24*1000);
		setCookie1(name,value,expiredate);
    }
}
function setCookie1(name, value, expire) {
   document.cookie = name + "=" + escape(value)  + ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) ;
}

// revised 10/9/2006 -jp -for faster performance with longer lists
// revised 5/3/2007 -jp - looking for a 3rd argument in the value to make the selection (for sublists)
function checkAll(objCB,arrFlds) {
	// locate all checkboxes except for the indicator
	// example: <input type="checkbox" id="selectAll_1" checked onclick="checkAll(this,this.form.contact);" />
	// the inputs should all have the same name i.e. "contact" in this example	
	var chk = objCB.checked;
	var fld = 0;
	// 10/17/2006 - jp - bug found when only one checkbox is in the array
	if (arrFlds.type == 'checkbox') {
		arrFlds.checked = chk;
		return true;
	}
	// if multiple are found, check them all
	if(arrFlds.length) {
		fld = arrFlds.length;
		for(var j=0;j<fld;j++) {
			if(!arrFlds[j].disabled) {
				if(arguments[2]) {	// if there is a third value, check for the value in the cb
					if(arrFlds[j].id.indexOf(arguments[2]) >= 0) {
						arrFlds[j].checked = chk;
					}
				} else {
					arrFlds[j].checked = chk;
				}
				checkThisBox(arrFlds[j]);
			}
		}
		return true;
	} 
}

var allowedKeys = new Array();
allowedKeys = [8,9,16,17,18,19,27,33,34,35,36,37,38,39,40,44,45,46,91,116,144,145];
/*
	Allowed IE/Firefox keycodes
	8	BACKSPACE
	9	TAB
	16	SHIFT
	17	CTRL
	18	ALT
	19	BREAK
	27	ESC
	
	33	PAGE UP
	34	PAGE DOWN
	35	END
	36	HOME
	37	ARROW LEFT
	38	ARROW UP
	39	ARROW RIGHT
	40	ARROW DOWN
	44	PRINT SCREEN
	45	INSERT
	46	DELETE
	
	91	WINDOWS
	116	F5
	144	NUM LOCK
	145	SCROLL LOCK
	
*/

/*
	Usage:
	<textarea name="comment_tx" id="comment_tx" cols="50" rows="5" maxlength="2000"
		onkeypress="return isMaxLength(this,event);"
		onkeyup="return isMaxLength(this,event);"
		style="overflow:visible;height:100px;"></textarea>
*/
function isMaxLength(obj,e) {
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute('maxlength')) : '';
	
	var msgID = obj.id + '_msg';
	var msg = document.getElementById(msgID);
	// check for message text
	if (!msg) {
		msg = document.createElement('div');
		msg.id = msgID;
		msg.className = 'small';
		obj.parentNode.appendChild(msg);
	}
	msg.innerHTML = obj.value.length + ' of ' + mlength + ' characters used';
	
	var isAllowedKey = false;
	//alert(e.keyCode);
	for (i=0;i<allowedKeys.length;i++) {
		if(parseInt(e.keyCode) == parseInt(allowedKeys[i])) {
			//alert(e.keyCode);
			isAllowedKey = true;
			break;
		}
	}
	if(isAllowedKey) {
		return true;
	}
	//alert('continuing');
	
	if (obj.getAttribute && obj.value.length==mlength) {
		return false;
	}
	if (obj.getAttribute && obj.value.length>mlength) {
		obj.value=obj.value.substring(0,mlength);
		return false;
	}
	return true;
}

var allCaps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numChars = '0123456789';
var realNumChars = numChars + '-.';
var phoneChars = numChars + '-';
var dateChars = numChars + '/';

// USAGE: <input type="text" onKeyPress="return allowChar(this,phoneChars,event);">
function allowChar(obj,allowedChars,e) {
	var key = '';
	var KEY_SPECIAL = '';
	var isAllowedKey = false;

	for (i=0;i<allowedKeys.length;i++) {
		if(parseInt(e.keyCode) == parseInt(allowedKeys[i])) {
			//alert(e.keyCode);
			isAllowedKey = true;
			break;
		}
	}
	if(isAllowedKey) {
		return true;
	}

	if(document.all) {
		key = String.fromCharCode(e.keyCode).toLowerCase();		// IE
		if (allowedChars.indexOf(key)<0) {
			return false;
		}
	} else {
		key = String.fromCharCode(e.which).toLowerCase();		// Firefox/Netscape
		if (allowedChars.indexOf(key)<0) {
			return false;
		}
	}
}

function jump(thisNum,e,max,action) {
    if (document.layers) {
        if (e.target.value.length >= max)
            eval(action);
    }
    else if (document.all){
        if (thisNum.value.length > (max-1))
            eval(action);
    }
}
function insertDash() { 
	var TaxIDLength;
  	TaxIDLength = document.forms[0].TaxID.value.length;
  	if (TaxIDLength==2){
  		document.forms[0].TaxID.value += "-";
  	}
  	var SSNLength;
  	SSNLength = document.forms[0].SSN.value.length;
  	if (SSNLength==3 || SSNLength==6){
  		document.forms[0].SSN.value += "-";
  	}
}
	
function loadAndStripe() {	
	// automatically stripe the table, if any are found
	var docTable = document.getElementsByTagName('table');
	for(var i=0;i<docTable.length;i++) {
		if(docTable[i].className.indexOf('report') >= 0) {
			stripeTable(docTable[i]);
			//docTable[i].style.border = '1px solid red';
		}
	}
	//stripeTable(document.getElementById('summaryTable'));
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function checkShape(s) {
	if(s=='Other') document.getElementById('specify').style.display = ''
	else document.getElementById('specify').style.display = 'none'
}

function confirmDelete() {
	return confirm("Please confirm you would like to remove this item.\n[ WARNING: This action is irreversible. ]");
}

// automatically sets focus to the first non-empty field
function setFocus() {
	for(z=0;z<document.forms.length;z++) {
		for (i=0;i<document.forms[z].elements.length;i++) {
			if(document.forms[z].elements[i].value == '' 
				&& document.forms[z].elements[i].getAttribute("type") != 'hidden') {
				try {
					document.forms[z].elements[i].focus();
				} catch(e) {
					window.status = document.forms[z].elements[i].name + ' couldn\'t accept focus';
					var timer = window.setTimeout("window.status = 'Done.'",3*1000);
				} 
				break;
			}
		}
	}
}

function toggleLayer(o) {
	if(o.style.display == 'none') o.style.display = ''
	else o.style.display = 'none'
}

// form formatting functions
	// http://www.novell.com/documentation/extendas35/docs/help/books/TechFormValidation.html
	// USAGE:  <input name="phone" type="text" onBlur="formatPhone(this);">
	function formatPhone(obj) {
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{3}-\d{3}-\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting phone format 000-000-0000');
				
				obj.focus();
			}
			return bool;
		}
	}
	
	// USAGE:  <input name="DSN" type="text" onBlur="formatDSN(this);">
	function formatDSN(obj) {
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{3}-\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting DSN format 000-0000');
				obj.focus();
			}
			return bool;
		}
	}
	
	// USAGE:  <input name="dateInput" type="text" onBlur="formatDate(this);">
	function formatDate(obj) {	// assuming mm/dd/yyyy
		obj.className = '';
		if (obj.value != '') {
			var bool = formatString(obj.value,/\d{2}\/\d{2}\/\d{4}/);
			if (!bool) {	// error found
				obj.className = 'required';	
				alert('Expecting date format mm/dd/yyyy');
				obj.focus();
			}
			return bool;
		}
	}
	
	function formatString(str,pattern) {
		// format a string based on what is passed in 
		// 999-999-9999
		var retVal = true;
		//pattern = /\d{3}-\d{3}-\d{4}/;
		if (!pattern.test(str)) {
			//document.forms[0].elements[2].focus();
			retVal = false;
		}
		return retVal;
	}
	
	/*
	var allCaps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var numChars = '0123456789';
	var phoneChars = numChars + '-';
	var dateChars = numChars + '/';
	// USAGE: <input type="text" onKeyPress="return allowChar(this,phoneChars);">
	function allowChar(obj,allowedChars) {
		var key = String.fromCharCode(event.keyCode).toLowerCase();
		if (allowedChars.indexOf(key)<0) {
			return false;
		}
	}
	*/


function clearSearch(obj) {
	if(obj.value == '- Search -') {
		obj.value = '';
	}
}

function doFCK(objTxtBx) {
	//FCKeditor( instanceName, width, height, toolbarSet, value )
	//var oFCKeditor = new FCKeditor( 'prob_desc', '100%', '200' ) ;		//, 'Basic'
	var oFCKeditor = new FCKeditor( objTxtBx.name, '100%', '250px' ) ;		//, 'Basic'
	oFCKeditor.BasePath = appHome + 'FCKeditor/';	// apphome defined dynamically in header
	if(objTxtBx.className.indexOf('basic')>=0) {
		oFCKeditor.ToolbarSet = 'Basic';	// 'Full';
	}
	//oFCKeditor.Value = '' ;
	//oFCKeditor.Create() ;
	oFCKeditor.ReplaceTextarea() ;
}

function initFCK() {
	var arrTA = document.getElementsByTagName('textarea');
	for(var j=0;j<arrTA.length;j++) {
		if(arrTA[j].className.indexOf('fck')>=0) {
			doFCK(arrTA[j]);
		}
	}
}

function selectPage() {
	var myLink = ge('nav').getElementsByTagName('a');
	var thisPage = location.href;
	// main navigation
	for(var i=myLink.length-1;i>=0;i--) {
		var thisHref = myLink[i].href;
		if(thisPage.indexOf(thisHref) >= 0) {
			myLink[i].className = 'selected';
			break;
		}
	}
	// sub-level navigation
	if(ge('nav2')) {
		var myLink = ge('nav2').getElementsByTagName('a');
		for(var i=myLink.length-1;i>=0;i--) {
			var thisHref = myLink[i].href;
			if(thisPage.indexOf(thisHref) >= 0) {
				myLink[i].className = 'selected';
				break;
			}
		}
	}
}

// iniitial functions to run onload (called from slideshow.js)
function init() {
	try {
		setFocus();
	} catch(e) {}
	try {
		loadAndStripe();
	} catch(e) {}
	try {
		initFCK();
	} catch(e) {}
	try {
		selectPage();
	} catch(e) {}
}

window.onload = init;
	